import requests

from Lib.zcm.assistant import FwVariables
from Lib.zcm.exception.TestException import TestException
from Lib.zcm.exception.errorcode import ErrorCode
import logging
logger = logging.getLogger()
logging.basicConfig(level=logging.DEBUG,
                    filemode='a',
                    format='%(asctime)s [%(levelname)-5s] %(threadName)13s (%(module)s:%(funcName)s:%(lineno)d) - %(message)s'
                    )


class Pod_Controller(object):
    # DEFAULT_PORTAL_URL = "http://10.45.80.3:52000/portal/zcm-application/"
    DEFAULT_PORTAL_URL = "https://dev.iwhalecloud.com:25000/portal/zcm-application/"
    def __init__(self, project_name, application_name):
        self._project_name = project_name
        self._application_name = application_name
        self.portal_base_url = FwVariables.get_value("ENV", "zcm_portal", self.DEFAULT_PORTAL_URL)

    def download_file(self, remote_file_path, local_file_path):
        url = self.portal_base_url + f"projects/{self._project_name}/applications/{self._application_name}/download"
        headers = self._get_auth_header()
        # 地址左右空格去除
        remote_file_path = remote_file_path.strip()
        local_file_path = local_file_path.strip()
        params = {"file": f"{remote_file_path}"}
        logger.info("url:{}".format(url))
        result = requests.get(url, params=params, headers=headers)
        if result.status_code != 200:
            raise TestException.by_error_code(ErrorCode.UNKNOWN, value=f"download failed! {result.content}")

        with open(local_file_path, "wb") as f:
            f.write(result.content)

    def upload_file(self, local_file_path, remote_path):
        url = self.portal_base_url + f"projects/{self._project_name}/applications/{self._application_name}/upload"
        headers = self._get_auth_header()
        remote_path = remote_path.strip()
        local_file_path = local_file_path.strip()
        params = {"dir": f"{remote_path}"}
        files = {'file': open(local_file_path, 'rb')}
        logger.info("url:{}".format(url))
        result = requests.post(url, params=params, files=files, headers=headers, stream=True)
        if result.status_code != 200:
            raise TestException.by_error_code(ErrorCode.UNKNOWN, value=f"upload file failed! {result.content}")
        return True

    def exec_command(self, command):
        url = self.portal_base_url + "projects/{}/applications/{}/exec?command={}".format(self._project_name, self._application_name, command)
        headers = self._get_auth_header()
        result = requests.post(url, headers=headers)
        if result.status_code != 200:
            raise TestException.by_error_code(ErrorCode.UNKNOWN, value=f"exec command failed! {result.content}")
        return result.text


    def _get_auth_header(self):
        return {"ZCM-Signature": "GB0zNennlh2Cvfd2/K58rnlOaZp1xyHmFPHg0iq/Atk=",
                "X-CSRF-TOKEN": "ZCM"}




if __name__ == '__main__':
    pod = Pod_Controller("UM_CD", "sic-backend-product-r92")
    pod.download_file("/usr/tomcat/tomcat9.0/sic_job/SIM_Vendor/EAS/INP2021060789 - Blank USIM.txt", "download.txt")
    # pod.download_file("/usr/tomcat/tomcat8.0/sic_job/SIM_Vendor/BBB/download2.txt", "download1.txt")
    # pod.upload_file("D:\\project\\test_project\\AUTO_TEST_DEMO\\Lib\\zcm\\utils\\INP20210114 - Blank USIM.txt", "/usr/tomcat/tomcat8.0/sic_job/SIM_Vendor/BBB/bak/")
